package com.woniu.daiquhua.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.woniu.daiquhua.entity.RepaymentPlan;
import com.woniu.daiquhua.entity.User;
import com.woniu.daiquhua.entity.UserMessage;
import com.woniu.daiquhua.service.UserMessageService;
import com.woniu.daiquhua.service.UserService;
import com.woniu.daiquhua.service.impl.UserServiceImpl;
import com.woniu.daiquhua.utils.RepaymentplanUtil;
import com.woniu.daiquhua.vo.UserMessageVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import static java.lang.System.out;

@RequestMapping("user")
@Controller
//把request作用域中的值 存储到session作用域 根据名称
@SessionAttributes("userInfo")
public class UserController {
    @Autowired
    UserService userService;
    @Value("${uploadImgPath}")
    String uploadImgPath;
    @Value("${webImgPath}")
    String webImgPath;
    @Autowired
    UserMessageService userMessageService;

    RepaymentplanUtil util = new RepaymentplanUtil();//还款计划的工具



    /**
     * 注册时验证该用户名是否存在，register.js异步请求
     */
    @RequestMapping("/findUAccount")
    public void findUAccount(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String registerAccount = req.getParameter("registerAccount");
        User user = userService.login(registerAccount);
        PrintWriter out = resp.getWriter();
        if (user==null){
            out.write("ok");
        }else {
            out.write("no");
        }
    }

    /**
     * 注册时验证该手机号码是否存在，register.js异步请求
     */
    @RequestMapping("/findMobile")
    public void findMobile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userMobile = req.getParameter("userMobile");

        User user = userService.findMobile(userMobile);
        PrintWriter out = resp.getWriter();
        if (user==null){
            out.write("ok");
        }else {
            out.write("no");
        }
    }

    @RequestMapping("/register")
    public String register(User user, Map map){


        String s = UUID.randomUUID().toString().replace("-", "");//得到一个随机盐值（不设定与唯一标识相同）
        user.setuSaltValue(s);
        Md5Hash md5Hash = new Md5Hash(user.getuPassword(),s);//MD5后的加密密码
        user.setuCodePass(md5Hash.toString());

        String uuid = UUID.randomUUID().toString().replaceAll("-",""); //用做用户的唯一标识CID
        user.setuUid(uuid);
        user.setuStatus(0);
        user.setuImage("");//设置默认头像

        int i=userService.insert(user);
        if(i>0){
            return "redirect:/register1.html";
        }else{
            return "redirect:/register.html";
        }
    }



    @RequestMapping("/login")
    public String login(String uName, String uPassword,Map map){
        User user = userService.login(uName);

        if(user == null){
            map.put("errorInfo", "账户不存在！");
            return "login";
        }else {
            if (user.getuPassword().equals(uPassword)) {
                //登录成功  存储session  发送一条短信
                map.put("userInfo",user);
                //访问 index.html页面
                return "redirect:/index.html" ;
            }else {
                map.put("errorInfo", "密码错误！");
                return "login";
            }
        }
    }

    @RequestMapping("/findOne")
    public String loan(Map map, HttpSession httpSession){
        User user =(User)httpSession.getAttribute("userInfo");
        UserMessage userMessage = userMessageService.findByCid(user.getuUid());
        if (userMessage!=null){
            BigDecimal rate = userMessage.getUmYearRate();
            BigDecimal multiply = rate.multiply(new BigDecimal("100"));
            double year = multiply.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            BigDecimal rate1 = userMessage.getUmDateRate();
            double date = rate1.doubleValue();
            date=date*100;

            userMessage.setYearRate(year);
            userMessage.setDateRate(date);
            System.out.println(userMessage);
        }
        map.put("userMessage",userMessage);
        return "loan";
    }

    @RequestMapping("/insetMessage")
    public String insetMessage(Map map, UserMessageVo userMessage, HttpSession session, @RequestParam("idcard1") MultipartFile idcard1, @RequestParam("idcard2")MultipartFile idcard2) throws IOException {
        User user =(User)session.getAttribute("userInfo");
        System.out.println(user);
        String name = user.getuName();
        String serverPath=uploadImgPath+name+"/";
        //获取w文件名字 a.jpg
        String filename1 = idcard1.getOriginalFilename();
        String filename2 = idcard2.getOriginalFilename();
        //获取UUID 来替换文件的名字
        filename1= UUID.randomUUID()+filename1;
        filename2= UUID.randomUUID()+filename2;
        File file = new File(serverPath+filename1);
        //判断file对象是否存在
        if (!file.exists()) {
            file.mkdirs();
        }

        File file1 = new File(serverPath+filename2);
        //判断file对象是否存在
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //上传文件
        idcard1.transferTo(file);
        idcard2.transferTo(file1);

        userMessage.setUmIdcardFacade(webImgPath+name+"/"+filename1);
        userMessage.setUmIdcardNegative(webImgPath+name+"/"+filename2);

        userMessage.setUmUid(user.getuUid());
        userMessage.setUmName(user.getuName());

        Random rand = new Random();
        if(userMessage.getUmSalary()==1){
            int randNum = rand.nextInt(5000)+5001;
            randNum=(int)randNum/100*100;
            BigDecimal bigDecimal = BigDecimal.valueOf(randNum);
            userMessage.setUmCreditLimit(bigDecimal);//信用的额度，5K-10K
            userMessage.setUmScoer(550);
            userMessage.setUmDateRate(new BigDecimal("0.0003"));
            userMessage.setUmYearRate(new BigDecimal("0.108"));
        }else if(userMessage.getUmSalary()==2){
            int randNum = rand.nextInt(10000)+10001;
            randNum=(int)randNum/100*100;
            BigDecimal bigDecimal = BigDecimal.valueOf(randNum);
            userMessage.setUmCreditLimit(bigDecimal);//信用的额度，10-20K
            userMessage.setUmScoer(600);
            userMessage.setUmDateRate(new BigDecimal("0.0004"));
            userMessage.setUmYearRate(new BigDecimal("0.144"));
        }else if(userMessage.getUmSalary()==3){
            int randNum = rand.nextInt(20000)+20001;
            randNum=(int)randNum/100*100;
            BigDecimal bigDecimal = BigDecimal.valueOf(randNum);
            userMessage.setUmCreditLimit(bigDecimal);//信用的额度，20K-40K
            userMessage.setUmScoer(650);
            userMessage.setUmDateRate(new BigDecimal("0.0005"));
            userMessage.setUmYearRate(new BigDecimal("0.18"));
        }else if(userMessage.getUmSalary()==4){
            int randNum = rand.nextInt(60000)+40001;
            randNum=(int)randNum/100*100;
            BigDecimal bigDecimal = BigDecimal.valueOf(randNum);
            userMessage.setUmCreditLimit(bigDecimal);//信用的额度，40K-100K
            userMessage.setUmScoer(750);
            userMessage.setUmDateRate(new BigDecimal("0.0002"));
            userMessage.setUmYearRate(new BigDecimal("0.072"));
        }else if(userMessage.getUmSalary()==5){
            int randNum = rand.nextInt(100000)+100001;
            randNum=(int)randNum/100*100;
            BigDecimal bigDecimal = BigDecimal.valueOf(randNum);
            userMessage.setUmCreditLimit(bigDecimal);//信用的额度，100K-200K
            userMessage.setUmScoer(800);
            userMessage.setUmDateRate(new BigDecimal("0.0003"));
            userMessage.setUmYearRate(new BigDecimal("0.108"));
        }
        if(userMessage.getUmRelation().equals("1")){
            userMessage.setUmRelation("父母");
        }else if(userMessage.getUmRelation().equals("2")){
            userMessage.setUmRelation("配偶");
        }else if(userMessage.getUmRelation().equals("3")){
            userMessage.setUmRelation("子女");
        }
        user.setuStatus(1);
        userService.updatestatus(user);
        userMessageService.insert(userMessage);
        System.out.println(userMessage);
        map.put("user",user);
        return "loan";
    }



    @RequestMapping("/showplan")
    public void showplan(HttpServletRequest req, HttpServletResponse resp,HttpSession session) throws IOException {
        User user =(User)session.getAttribute("userInfo");
        UserMessage user1 = userMessageService.findByCid(user.getuUid());
        BigDecimal umDateRate = user1.getUmDateRate();//获得用户的日利率
        int num = Integer.parseInt(req.getParameter("num"));//期数
        String moneyStr = req.getParameter("money");//借款金额
        BigDecimal money = new BigDecimal(moneyStr);//借款金额
        String value = req.getParameter("value");
        if(value.equals("1")){//选择了等额本息

            List<RepaymentPlan> list = util.Equalinstallmentsofprincipalandinterest(3, umDateRate, money, num);
            String info = JSON.toJSONString(list);
            resp.getWriter().write(info);
        }else if(value.equals("2")){//选择了等额本金
            List<RepaymentPlan> list = util.equalprincipal(3, umDateRate, money, num);
            String info = JSON.toJSONString(list);
            resp.getWriter().write(info);
        }

    }


}
